package com.smile.service.config;


//package com.takumilove.mqtt.config;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * MQTT 消息发送配置
 */
@Configuration
@RequiredArgsConstructor
public class MqttOutBoundConfiguration {

//    private final MqttConfigurationProperties mqttConfigurationProperties;
    private final MqttPahoClientFactory mqttPahoClientFactory;
    @Value("${spring.mqtt.server-url}")
    private String url;

    @Value("${spring.mqtt.username}")
    private String username;

    @Value("${spring.mqtt.password}")
    private String password;

    private String clientId = "heartbeat-nhb-123456";

    /**
     * 配置发送消息的通道
     */
    @Bean
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

    /**
     * 配置 MQTT 消息发送处理器
     */
    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutboundMessageHandler() {
        System.out.println("创建mqtt连接");
        MqttPahoMessageHandler handler = new MqttPahoMessageHandler(
                url,
                clientId,
                mqttPahoClientFactory
        );
        handler.setDefaultQos(0); // 设置默认QoS：最多一次
        handler.setDefaultTopic("default"); // 设置默认主题
        handler.setAsync(true); // 异步发送消息
        return handler;
    }
}
